
//
//  UIImageView+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 2019/8/2.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import Foundation
import Kingfisher
import SDWebImage

//MARK: - 图片视图
extension UIImageView {

    //MARK: 初始化方法
    ///快捷生成UIImageView
    convenience init(imageName:String =  "",cornerRadius:CGFloat?=nil,borderColor:UIColor?=nil,borderWidth:CGFloat?=nil) {
        self.init()
        self.image = UIImage(named:imageName)
        self.makeCornerRadius(cornerRadius, borderColor: borderColor, borderWidth: borderWidth)
    }
    
    convenience init(name:String? = nil) {
        self.init()
        if let imgName = name {
            self.image = UIImage(named:imgName)
        }
    }
    
    convenience init(name:String? = nil, mode:UIView.ContentMode? = .scaleToFill, clips:Bool = false, cornerRadius:CGFloat? = nil) {
        self.init()
        if let imgName = name {
            self.image = UIImage(named:imgName)
        }
        if let contentMode = mode {
            self.contentMode = contentMode
        }
        self.clipsToBounds = clips
        if let cornerRadius = cornerRadius {
            self.cornerRadius = cornerRadius
        }
    }
    
    convenience init(frame:CGRect? = nil, name:String? = nil, mode:UIView.ContentMode? = .scaleToFill, clips:Bool = false, cornerRadius:CGFloat? = nil) {
        self.init()
        if let frameValue = frame {
            self.frame = frameValue
        }
        if let imgName = name {
            self.image = UIImage(named:imgName)
        }
        if let contentMode = mode {
            self.contentMode = contentMode
        }
        self.clipsToBounds = clips
        if let cornerRadius = cornerRadius {
            self.cornerRadius = cornerRadius
        }
    }

    ///快捷生成UIImageView
    class func aspectFitImageView() -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = UIView.ContentMode.scaleAspectFit
        imageView.clipsToBounds = true
        return imageView
    }
    
    ///快捷生成UIImageView
    class func aspectFillImageView() -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = UIView.ContentMode.scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }
    
    func setImageWithTintColor(_ tintColor:UIColor,imageName:String) {
        self.tintColor = tintColor
        let image = UIImage(named:imageName)?.withRenderingMode(.alwaysTemplate)
        self.image = image
    }
    
    //MARK: 加载本地图片，包括gif
    /// 加载本地图片，包括gif (慎用gif图，这个库不稳定，会是不是崩溃)
    /// - Parameters:
    ///   - fileURL: 本地图片路径
    ///   - placeholder: <#placeholder description#>
    func loadLocalImage(_ fileURL:String?, placeholder:DefaultImageType = .none){
        guard let fileURL = fileURL else {
            return
        }
        let url = URL(fileURLWithPath: fileURL)
//        PPLog("本地图片：\(url)")
        /*
         两种实现方式：
         方式1：
         let provider = LocalFileImageDataProvider(fileURL: url)
         self.kf.setImage(with: provider)
         **/
        let provider = LocalFileImageDataProvider(fileURL: url)
        if url.pathExtension == "gif" {
            //加载gif动图
            KF.url(url, cacheKey: "\(url)-imageview").set(to: self)
        }else{
            self.kf.setImage(with: provider)
        }
    }
    
    //MARK: 加载网络图片
    /// 加载网络图片
    /// - Parameters:
    ///   - webUrl: <#webUrl description#>
    ///   - placeholder: <#placeholder description#>
    func loadImage(_ webUrl:String?, placeholder:DefaultImageType = .none){
        guard let webUrl = webUrl else{
            self.image = UIImage(named: placeholder.rawValue)
            return
        }
        if webUrl.isValidURL() == false {
            self.image = UIImage(named: placeholder.rawValue)
            return
        }
        /// 是否包含中文 -> 转换UTF-8编码
        var new_webUrl = webUrl
        if new_webUrl.includeChinese { new_webUrl = new_webUrl.addPE() }
        let url = URL(string: new_webUrl)
        
        if url?.pathExtension == "gif" {
            //加载gif动图
            KF.url(url, cacheKey: "\(url)-imageview").set(to: self)
        }else{
            //加载普通图
            let progressive = ImageProgressive(
                isBlur: true,
                isFastestScan: true,
                scanInterval: 0.1
            )
            self.kf.setImage(
                with: url,
                placeholder: UIImage(named: placeholder.rawValue),
                options: [.loadDiskFileSynchronously,
                          .progressiveJPEG(progressive)],
                progressBlock: { receivedSize, totalSize in
                    //PPLog("图片下载中：\(receivedSize)/\(totalSize)， 地址：\(String(describing: webUrl))")
                },
                completionHandler: { result in
                    //PPLog("Finished \(result)")
            })
            
            //删除缓存
//            KingfisherManager.shared.cache.removeImage(
//                forKey: URL对象.cacheKey,
//                processorIdentifier: self.processor.identifier,
//                callbackQueue: .mainAsync,
//                completionHandler: {
//                    self.loadImage()
//            }
//            )
        }
    }
    
    //MARK: 加载网络图片
    /// 加载网络图片
    /// - Parameters:
    ///   - webUrl: <#webUrl description#>
    ///   - placeholder: <#placeholder description#>
    func loadImage(_ webUrl:String?, _ defaultImage:UIImage?){
        guard let webUrl = webUrl else{
            self.image = defaultImage
            return
        }
        
        /// 是否包含中文 -> 转换UTF-8编码
        var new_webUrl = webUrl
        if new_webUrl.includeChinese { new_webUrl = new_webUrl.addPE() }
        let url = URL(string: new_webUrl)
        
        if url?.pathExtension == "gif" {
            //加载gif动图
            KF.url(url, cacheKey: "\(url)-imageview").set(to: self)
        }else{
            //加载普通图
            let progressive = ImageProgressive(
                isBlur: true,
                isFastestScan: true,
                scanInterval: 0.1
            )
            self.kf.setImage(
                with: url,
                placeholder: defaultImage,
                options: [.loadDiskFileSynchronously,
                          .progressiveJPEG(progressive)],
                progressBlock: { receivedSize, totalSize in
                    //PPLog("图片下载中：\(receivedSize)/\(totalSize)， 地址：\(String(describing: webUrl))")
                },
                completionHandler: { result in
//                    PPLog("Finished \(result)")
            })
            
            //删除缓存
//            KingfisherManager.shared.cache.removeImage(
//                forKey: URL对象.cacheKey,
//                processorIdentifier: self.processor.identifier,
//                callbackQueue: .mainAsync,
//                completionHandler: {
//                    self.loadImage()
//            }
//            )
        }
    }
    
    //MARK: 加载网络头像
    /// 加载网络头像，头像使用SDWebImage框架，主要是能解决webp图片和无后缀图片流
    /// - Parameters:
    ///   - webUrl: <#webUrl description#>
    ///   - placeholder: <#placeholder description#>
    func loadAvatar(_ webUrl:String?, placeholder:DefaultImageType = .avatar){
        guard let webUrl = webUrl else{
            self.image = UIImage(named: placeholder.rawValue)
            return
        }
        if webUrl.isValidURL() == false {
            self.image = UIImage(named: placeholder.rawValue)
            return
        }
        let url = URL(string: webUrl)
        self.sd_setImage(with: url, placeholderImage: UIImage(named: placeholder.rawValue), options: .progressiveLoad, context: nil)
    }
}
